package com.wrt.sps.mgt.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wrt.sps.entity.Results;
import com.wrt.sps.mgt.entity.Writing;
import com.wrt.sps.mgt.service.UserService;
import com.wrt.sps.mgt.service.WritingService;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 * 统计接口
 * 
 * @author 文瑞涛
 * @date 2021年1月12日 下午2:31:07
 */
@RestController
@RequestMapping("/mgt/statistics")
public class StatisticsController {
	
	@Resource
	private UserService userService;
	@Resource
	private WritingService writingService;

	/**
	 * 
	 * 基础数量统计
	 * 展示用户数和文章数
	 * 
	 * @return 统计结果
	 */
	@GetMapping("/base")
	public Results base() {
		Map<String, List<Long>>countMap = new HashMap<>(2);
		countMap.put("user", userService.countUsers());
		countMap.put("writing", writingService.countWritings());
		return Results.success(null, countMap);
	}
	
	/**
	 * 
	 * 文章分类数量统计
	 * 展示用户数和文章数
	 * 
	 * @return 统计结果
	 */
	@GetMapping("/writing_type")
	public Results writingType() {
		Map<String, Object>countMap = new HashMap<>(2);
		countMap.put("name", Writing.typeNames());
		countMap.put("data", parseMap(writingService.countWritingsByType()));
		return Results.success(null, countMap);
	}
	
	/**
	 * 
	 * 数据转换，将有效map集合内容，转换为echarts可用集合
	 * 
	 * @param map 待转换的集合
	 * 
	 * @return 转换后的集合
	 */
	private List<EchartsData> parseMap(Map<Writing.Type, Long> map){
		if(CollectionUtils.isEmpty(map.keySet())) {
			return Collections.emptyList();
		} else {
			Set<Writing.Type>keys = map.keySet();
			List<EchartsData> result = new ArrayList<>(keys.size());
			for(Writing.Type type: keys) {
				result.add(new EchartsData(Writing.typeName(type), String.valueOf(map.get(type))));
			}
			return result;
		}
	}
	
	@Getter
	@Setter
	@AllArgsConstructor
	private static class EchartsData{
		/**
		 * 名称
		 */
		private String name;
		/**
		 * 数值
		 */
		private String value;
	}
}
